using System.Windows.Media;
using Newtonsoft.Json.Linq;
using TicTacToe.Core;

namespace _3DTicTacToe.Net
{
    static class Serialization
    {
        public static JObject Serialize(this Turn turn)
        {
            return new JObject(
                new JProperty("Player", Serialize(turn.Player)),
                new JProperty("X1", turn.X1),
                new JProperty("X2", turn.X2),
                new JProperty("X3", turn.X3));
        }

        public static JObject Serialize(this Player player)
        {
            return new JObject(
                new JProperty("Name", player.Name),
                new JProperty("Color", new JArray(player.Color.A, player.Color.R, player.Color.G, player.Color.B)),
                new JProperty("ID", player.ID));
        }

        public static Turn DeserializeTurn(JObject obj)
        {
            var player = DeserializePlayer((JObject)obj["Player"]);
            var x1 = (int)obj["X1"];
            var x2 = (int)obj["X2"];
            var x3 = (int)obj["X3"];

            return new Turn(player, x1, x2, x3);
        }

        public static Player DeserializePlayer(JObject obj)
        {
            var name = obj.Value<string>("Name");
            var id = obj.Value<string>("ID");
            var ca = obj.Value<JArray>("Color");

            var a = (byte)(int)ca[0];
            var r = (byte)(int)ca[1];
            var g = (byte)(int)ca[2];
            var b = (byte)(int)ca[3];

            return new Player(name, new Color {A = a, R = r, G = g, B = b}, id);
        }
    }
}